# pip install python-dotenv
from dotenv import load_dotenv; load_dotenv()

from langchain_community.agent_toolkits.playwright.toolkit import PlayWrightBrowserToolkit
from langchain_community.tools.playwright.utils import create_async_playwright_browser

from langchain import hub
from langchain_openai import ChatOpenAI
from langchain.agents import AgentExecutor, create_structured_chat_agent

import json

async_browser = create_async_playwright_browser()
toolkit = PlayWrightBrowserToolkit.from_browser(async_browser=async_browser)
tools = toolkit.get_tools()
for tool in tools: 
    print(f'**** tool.name[{tool.name}] ****\ntool.description: {tool.description}')
    # tool.args json格式化输出
    json_str = json.dumps(tool.args, indent=4, ensure_ascii=False)
    print(f'tool.args: \n{json_str}\n')

# LLM不稳定，对于这个任务，可能要多跑几次才能得到正确结果
llm = ChatOpenAI(model="gpt-3.5-turbo", temperature=0.5)  

prompt = hub.pull("hwchase17/structured-chat-agent")
print(prompt.messages[0].prompt.template)

# initialize_agent函数的弃用 agent_chain = initialize_agent(
agent = create_structured_chat_agent(tools=tools, llm= llm, prompt=prompt)
agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)

async def main():
    # Chain.arun方法的弃用 response = await agent_chain.arun("What are the headers on python.langchain.com?")
    response = await agent_executor.ainvoke(
        {
            "input": "What are the headers on python.langchain.com?"
            
        }
    )
    print(response)

import asyncio
loop = asyncio.get_event_loop()
loop.run_until_complete(main())